//
//  ReadMainViewController.m
//  SmileRead
//
//  Created by dllo on 15/8/24.
//  Copyright (c) 2015年 JIZ. All rights reserved.
//

#import "ReadMainViewController.h"
#import "AsyncPOSTParser.h"
#import "Path.h"
#import "FileNameList.h"
#import "AFHTTPRequestOperationManager.h"
#import "ReadModel.h"
#import "ReadCell.h"
#import "HeaderModel.h"
#import "MyViewOfScrollView.h"
#import "ReadSecondViewController.h"
#import "MJRefresh.h"
#import "MyNETLunBoTu.h"
#import "AppDelegate.h"
#import "SearchViewController.h"


@interface ReadMainViewController ()<UITableViewDataSource, UITableViewDelegate>

{
    NSInteger _count;
    NSInteger _i;
}

@property (nonatomic, retain) NSMutableArray *arrayOfdata;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *arrayOfheader;
@property (nonatomic, retain) NSMutableArray *arrayOfHImage;
@property (nonatomic, retain) UIImageView *backImageView;

@end

@implementation ReadMainViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.arrayOfheader = [NSMutableArray array];
        self.arrayOfdata = [NSMutableArray array];
        self.arrayOfHImage = [NSMutableArray array];
    }
    return self;
}

- (void)dealloc
{
   
    [_backImageView release];
    [_arrayOfheader release];
    [_arrayOfHImage release];
    [_tableView release];
    [_arrayOfdata release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated
{
  
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"阅";
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(search)] autorelease];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self handelParser];
}

// 点击进入搜索界面
- (void)search
{
    SearchViewController *search = [[SearchViewController alloc] init];
    [search receiveArray:self.arrayOfdata ident:@"read"];
    [self.navigationController pushViewController:search animated:YES];
    [search release];
}

- (void)handelParser
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager.requestSerializer setValue:@"pianke_session=eyJpdiI6IjFmVWVxQVJOSjZTSlhqTTFrRFg2cWc9PSIsInZhbHVlIjoiNXAxdnRTSnFWRUZEQVI5MFZMMGkyVjJRZUpvNlIyRWw3T0lGbVdsOGpjTWRmTkNHNHhyWVRBNVpZb3lycWk4K3FBM1NPd0owMmh2Z1dTNjU3WjJxNHc9PSIsIm1hYyI6ImU1NTgwNzdjMjA3ZTQ2MjAwOGExMzU0OTA2Yzg4MTM5ODM0N2M0ZTQ5YmFlZDFlZTYwNDdlNWJjYTZjZGY1ODMifQ%3D%3D" forHTTPHeaderField:@"Cookie"];
    
    NSDictionary *dic = @{@"sort" : @"addtime", @"start" : @"0", @"client" : @"2", @"typeid" : @"14", @"limit" : @"10"};
    
    [AsyncPOSTParser asyncPOSTParserWithURLString:LY_Read fileName:FILE_Read pamarters:dic block:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = [[dic objectForKey:@"data"] objectForKey:@"list"];
        for (int i = 0; i < array.count; i++) {
            ReadModel *model = [[ReadModel alloc] init];
            [model setValuesForKeysWithDictionary:array[i]];
            [self.arrayOfdata addObject:model];
            if (i % 3 == 0 && i != 0) {
                [self.arrayOfheader addObject:model];
                if (self.arrayOfheader.count == 3) {
                    break;
                }
            }
        }
        if (self.arrayOfheader.count > 0) {
            ReadModel *model1 = [self.arrayOfheader firstObject];
            ReadModel *model2 = [self.arrayOfheader lastObject];
            [self.arrayOfheader addObject:model1];
            [self.arrayOfheader insertObject:model2 atIndex:0];
        }
        [self createTableView];
        [self createheaderView];
    }];
}

- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64 * heightFit) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.separatorColor = [UIColor grayColor];
    //self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    [self refresh];
    [_tableView release];
}


- (void)createheaderView
{
    MyNETLunBoTu *lun = [[[MyNETLunBoTu alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 220 * heightFit) arrayOfImage:self.arrayOfheader] autorelease];
    self.tableView.tableHeaderView = lun;
}


// 上拉加载, 下拉刷新
-(void)refresh
{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _i = 0;
        // 删除原有数据
        NSString *path = [Path pathOfLibraryWithFileName:FILE_Read];
        NSFileManager *file = [NSFileManager defaultManager];
        if ([file isExecutableFileAtPath:path]) {
            [file removeItemAtPath:path error:nil];
        }
        
        
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        
        [manager.requestSerializer setValue:@"pianke_session=eyJpdiI6IjFmVWVxQVJOSjZTSlhqTTFrRFg2cWc9PSIsInZhbHVlIjoiNXAxdnRTSnFWRUZEQVI5MFZMMGkyVjJRZUpvNlIyRWw3T0lGbVdsOGpjTWRmTkNHNHhyWVRBNVpZb3lycWk4K3FBM1NPd0owMmh2Z1dTNjU3WjJxNHc9PSIsIm1hYyI6ImU1NTgwNzdjMjA3ZTQ2MjAwOGExMzU0OTA2Yzg4MTM5ODM0N2M0ZTQ5YmFlZDFlZTYwNDdlNWJjYTZjZGY1ODMifQ%3D%3D" forHTTPHeaderField:@"Cookie"];
        
        NSDictionary *dic = @{@"sort" : @"addtime", @"start" : @"0", @"client" : @"2", @"typeid" : @"14", @"limit" : @"10"};
        
        [AsyncPOSTParser asyncPOSTParserWithURLString:LY_Read fileName:FILE_Read pamarters:dic block:^(NSData *data) {
            
            [self.arrayOfdata removeAllObjects];
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *array = [[dic objectForKey:@"data"] objectForKey:@"list"];
            for (int i = 0; i < array.count; i++) {
                ReadModel *model = [[ReadModel alloc] init];
                [model setValuesForKeysWithDictionary:array[i]];
                [self.arrayOfdata addObject:model];
            }
            [self.tableView reloadData];
            [self.tableView.header endRefreshing];
        }];
    }];
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _count = (_i + 1) * 10;
        _i++;
        NSString *start = [NSString stringWithFormat:@"%ld", _count];
        
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        [manager.requestSerializer setValue:@"pianke_session=eyJpdiI6IjFmVWVxQVJOSjZTSlhqTTFrRFg2cWc9PSIsInZhbHVlIjoiNXAxdnRTSnFWRUZEQVI5MFZMMGkyVjJRZUpvNlIyRWw3T0lGbVdsOGpjTWRmTkNHNHhyWVRBNVpZb3lycWk4K3FBM1NPd0owMmh2Z1dTNjU3WjJxNHc9PSIsIm1hYyI6ImU1NTgwNzdjMjA3ZTQ2MjAwOGExMzU0OTA2Yzg4MTM5ODM0N2M0ZTQ5YmFlZDFlZTYwNDdlNWJjYTZjZGY1ODMifQ%3D%3D" forHTTPHeaderField:@"Cookie"];
        NSDictionary *dic = @{@"sort" : @"addtime", @"start" : start, @"client" : @"2", @"typeid" : @"14", @"limit" : @"10"};
        [AsyncPOSTParser asyncPOSTParserWithURLString:LY_Read fileName:FILE_Read pamarters:dic block:^(NSData *data) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *array = [[dic objectForKey:@"data"] objectForKey:@"list"];
            for (int i = 0; i < array.count; i++) {
                ReadModel *model = [[ReadModel alloc] init];
                [model setValuesForKeysWithDictionary:array[i]];
                [self.arrayOfdata addObject:model];
            }
            if (data != nil) {
                [self.tableView.footer endRefreshing];
            }
            [self.tableView reloadData];
        }];
    }];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayOfdata.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ident = @"cell";
    ReadCell *cell = [tableView dequeueReusableCellWithIdentifier:ident];
    if (cell == nil) {
        cell = [[[ReadCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ident] autorelease];
    }
    
    if (self.arrayOfdata.count > 0) {
        cell.model = self.arrayOfdata[indexPath.row];
        //cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 150 * heightFit;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%ld", indexPath.row);
    
    ReadSecondViewController *second = [[ReadSecondViewController alloc] init];
    ReadModel *model = self.arrayOfdata[indexPath.row];
    [second receivewithModel:model];

    AppDelegate *tempAppdelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    [tempAppdelegate.window.rootViewController presentViewController:second animated:YES completion:^{
        
    }];
    [second release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
